<template>
    <div class="mainCenter">
        <div class="title">{{ title }}</div>
        <div class="mainCenterBox">
            <el-form label-width="120" :model="baseInfo" :rules="rules" ref="formRef">
                <div class="left">
                    <el-form-item label="用户姓名" prop="relname">
                        <el-input type="text" v-model="baseInfo!.relname"></el-input>
                    </el-form-item>
                    <el-form-item label="用户生日">
                        <el-date-picker v-model="baseInfo.birth" type="date" placeholder="选择生日" />
                    </el-form-item>
                    <el-form-item label="用户性别">
                        <el-radio-group v-model="baseInfo.gender" class="ml-4">
                            <el-radio label="1" size="large">男</el-radio>
                            <el-radio label="2" size="large">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="用户手机号" prop="phonenumber">
                        <el-input type="text" v-model="baseInfo!.phonenumber"></el-input>
                    </el-form-item>
                    <el-form-item label="用户邮箱" prop="mail">
                        <el-input type="text" v-model="baseInfo!.mail"></el-input>
                    </el-form-item>
                    <el-form-item label="用户身份证号">
                        <el-input type="text" v-model="baseInfo!.pid"></el-input>
                    </el-form-item>
                    <el-form-item label="账号状态">
                        <el-switch v-model="isState"></el-switch>
                    </el-form-item>
                    <el-form-item label="用户备注">
                        <el-input type="textarea" v-model="baseInfo!.remark" :row="5" show-word-limit maxlength="30"
                            resize="none"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" class="save" @click="submitForm(formRef)">保存</el-button>
                    </el-form-item>
                </div>
                <div class="right">
                    <el-form-item class="imgBox">
                        <div class="avatar-uploader" style="display: flex; justify-content: center; align-items: center;">
                            <el-icon v-if="baseInfo.avatar == ''" style="color: gainsboro;font-size: 45px;">
                                <Plus />
                            </el-icon>
                            <img :src="baseInfo.avatar" alt="" v-else>
                        </div>
                        <el-upload :http-request="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                            :show-file-list="false">
                            <el-button type="primary" plain>上传头像</el-button>
                        </el-upload>
                    </el-form-item>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reqAddUser, reqCheckMail, reqCheckPhone, reqGetUser, reqEditManger} from '@/api/common';
import { User } from '@/types/user';
import { tip } from '@/utils/alert';
import { getBase64 } from '@/utils/commonUse';
import { FormRules, UploadProps, FormInstance } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { computed, onMounted, reactive, ref ,watch} from 'vue';
import Cloud from 'leancloud-storage';
const route = useRoute()
const router = useRouter()
const title = ref<string>('')
const isState = ref<boolean>(false)
const baseInfo = ref<User>({
    uid: "",
    avatar: "",
    birth: "",
    gender: "",
    mail: "",
    nickname: "",
    phonenumber: "",
    pid: "",
    relname: "",
    remark: "",
    state: 0

})

const isPhoneNumber = ref<string>('')
const isMail = ref<string>('')
const isAvatar=ref<string>('')


watch(()=>isState.value,()=>{
    if(isState.value){
        baseInfo.value.state = 1
    }else{
        baseInfo.value.state = 0
    }
})


const formRef = ref<FormInstance>()
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const imgType = ['image/jpeg', 'image/png']
    if (imgType.indexOf(rawFile.type) == -1) {
        tip('图片格式为jpg', 'warning')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        tip('图片大小应为2MB', 'warning')
        return false
    }
    return true
}

const getUser = (uid: string) => {
    reqGetUser(uid).then(res => {
        baseInfo.value = res.data.data
        isPhoneNumber.value = baseInfo.value.phonenumber as string
        isAvatar.value=baseInfo.value.avatar as string
        isMail.value = baseInfo.value.mail as string
        if(baseInfo.value.state!=1){
            isState.value=false
            console.log(isState.value);
        }else{
            isState.value=true
        }
    })
}

const handleAvatarSuccess = (info: { file: any; }) => {
    getBase64(info.file, (base64: any) => {
        baseInfo.value.avatar = base64
    })
}

const checkName = (rules: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('请输入真实名字'))
    } else {
        callback()
    }
}
const checkMail = (rules: any, value: any, callback: any) => {
    let reg = /^([a-zA-Z\d][\w-]{2,})@(\w{2,})\.([a-z]{2,})(\.[a-z]{2,})?$/
    if (value == '') {
        callback(new Error('请输入邮箱'))
    } else if (value != isMail.value) {
        if (!reg.test(value)) {
            callback(new Error('邮箱格式错误'))
        } else {
            reqCheckMail(value).then(res => {
                if (res.data.code != "200") {
                    callback(new Error('邮箱已存在'))
                } else {
                    callback()
                }
            })
        }
    } else {
        callback()
    }
}

const checkPhoneNumber = (rules: any, value: any, callback: any) => {
    let reg = /^1[3-9]\d{9}$/
    if (value == '') {
        callback(new Error('请输入手机号'))
    }
    else if (value != isPhoneNumber.value) {
        if (!reg.test(value)) {
            callback(new Error('手机号式错误'))
        } else {
            reqCheckPhone(value).then(res => {
                if (res.data.code != "200") {
                    callback(new Error('手机号已存在'))
                } else {
                    callback()
                }
            })
        }
    } else {
        callback()
    }
}

const rules = reactive<FormRules>({
    relname: [{ validator: checkName, trigger: 'blur', required: true }],
    mail: [{ validator: checkMail, trigger: 'blur', required: true }],
    phonenumber: [{ validator: checkPhoneNumber, trigger: 'blur', required: true }],
})




onMounted(() => {
    if (route.query.uid) {
        getUser(route.query.uid as string)
        title.value = "修改用户"
    } else {
        title.value = "新增用户"
    }
})



const upLoadImgServer = async (state:boolean) => {
    if(isAvatar.value!=baseInfo.value.avatar){
        let cloudFile = new Cloud.File("avtarImg", { base64: baseInfo.value.avatar });
        let res: any = await cloudFile.save()
        baseInfo.value.avatar = res.attributes.url
    }
    
    // changeState()
    console.log(baseInfo.value);
    if(state==true){
        reqAddUser(baseInfo.value).then(res => {
        router.push('/users/userList')
    })
    }else{
        reqEditManger(baseInfo.value)
        router.push('/users/userList')
    }
}


const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            if (route.query.uid) {
                upLoadImgServer(false)
            } else {
                upLoadImgServer(true)
            }
        } else {
            console.log('error submit!')
            return false
        }
    })
}







</script>

<style scoped lang="scss">
.mainCenterBox {
    .el-form {
        width: 400px;
        display: flex;

        .imgBox {
            .avatar-uploader {
                height: 200px;
                width: 200px;
                border: 1px dashed var(--el-border-color);
                overflow: hidden;

                img {
                    width: 100%;
                    height: 100%;
                }
            }

            .el-button {
                margin-top: 20px;
                width: 200px;
            }
        }

        .el-form-item {
            .save {
                width: 400px;
            }
        }
    }
}
</style>